package cn.broadmax.boot.exception;

import cn.broadmax.boot.base.message.SResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @author jeff
 * @date 2020/6/14
 */
@Slf4j
@RestControllerAdvice
public class WebExceptionHandler {

    @ExceptionHandler(WebException.class)
    public SResult<Object> handleException(WebException e){
        log.debug(e.getMessage(), e);
        return SResult.warn(e.getMessage());
    }

    /**
     * 权限异常
     */
    @ExceptionHandler(AuthorityException.class)
    public SResult<Object> handleException(AuthorityException e){
        log.debug(e.getMessage(), e);
        return SResult.unauth(e.getMessage());
    }

    /**
     * 参数非法
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public SResult<Object> handleException(ConstraintViolationException e){
        log.debug(e.getMessage(), e);
        String message = e.getConstraintViolations().iterator().next().getMessage();
        return SResult.warn(message);
    }

    /**
     * 参数非法
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public SResult<Object> handleException(MethodArgumentNotValidException e){
        log.debug(e.getMessage(), e);
        String message = "参数异常";
        if(e.getBindingResult().getFieldError() != null){
            message = e.getBindingResult().getFieldError().getDefaultMessage();
        }
        return SResult.warn(message);
    }

    @ExceptionHandler(Exception.class)
    public SResult<Object> handleException(Exception e){
        log.error(e.getMessage(), e);
        return SResult.error("操作失败");
    }

}
